package net.adetech.dcweb.core.common.service.impl;

import net.adetech.utils.condition.ConditionEntity;
import net.adetech.utils.condition.ConditionTools;
import net.adetech.utils.condition.SQLEntity;
import net.adetech.utils.spring.PageBean;
import net.adetech.dcweb.core.common.service.ICommonAdminuserService;
import net.adetech.dcweb.core.common.entity.CommonAdminuser;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created by sunfeihu on 2016/10/20.
 */
@Service
public class CommonAdminuserServiceImpl implements ICommonAdminuserService {

    private final Logger logger = LoggerFactory.getLogger(CommonAdminuserServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public CommonAdminuser save(CommonAdminuser entity) {
        final String sql = " insert into common_adminuser (uuid,add_info,add_date,add_user,update_date,update_info,update_user,usern,password,is_use,login_count,last_login_date,laset_login_info,is_delete,role_no,real_name,police_no,sex,department_id,add_ip,update_ip,last_login_ip,phone) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        final CommonAdminuser finalEntity = entity;
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1, finalEntity.getUuid());
                ps.setObject(2, finalEntity.getAddInfo());
                if (null != finalEntity.getAddDate()) {
                    ps.setObject(3, new Timestamp(finalEntity.getAddDate().getTime()));
                } else {
                    ps.setObject(3, null);
                }
                ps.setObject(4, finalEntity.getAddUser());
                if (null != finalEntity.getUpdateDate()) {
                    ps.setObject(5, new Timestamp(finalEntity.getUpdateDate().getTime()));
                } else {
                    ps.setObject(5, null);
                }
                ps.setObject(6, finalEntity.getUpdateInfo());
                ps.setObject(7, finalEntity.getUpdateUser());
                ps.setObject(8, finalEntity.getUsern());
                ps.setObject(9, finalEntity.getPassword());
                ps.setObject(10, finalEntity.getIsUse());
                ps.setObject(11, finalEntity.getLoginCount());
                if (null != finalEntity.getLastLoginDate()) {
                    ps.setObject(12, new Timestamp(finalEntity.getLastLoginDate().getTime()));
                } else {
                    ps.setObject(12, null);
                }
                ps.setObject(13, finalEntity.getLasetLoginInfo());
                ps.setObject(14, finalEntity.getIsDelete());
                ps.setObject(15, finalEntity.getRoleNo());
                ps.setObject(16, finalEntity.getRealName());
                ps.setObject(17, finalEntity.getPoliceNo());
                ps.setObject(18, finalEntity.getSex());
                ps.setObject(19, finalEntity.getDepartmentId());
                ps.setObject(20, finalEntity.getAddIp());
                ps.setObject(21, finalEntity.getUpdateIp());
                ps.setObject(22, finalEntity.getLastLoginIp());
                ps.setObject(23, finalEntity.getPhone());
                return ps;
            }
        }, keyHolder);
        Long id = keyHolder.getKey().longValue();
        return this.find(id);
    }

    @Override
    public int delete(Long id) {
        final String sql = " update common_adminuser set is_delete = 1 where id = ? ";
        return jdbcTemplate.update(sql, new Object[]{
                id
        });
    }

    @Override
    public int update(CommonAdminuser entity) {
        final String sql = " update common_adminuser set add_info=?,update_info=?,usern=?,password=?,is_use=?,login_count=?,last_login_date=?,laset_login_info=?,role_no=?,real_name=?,police_no=?,sex=?,department_id=?,last_login_ip=?,phone=? where id = ?";
        return jdbcTemplate.update(sql, new Object[]{
                entity.getAddInfo(),
                entity.getUpdateInfo(),
                entity.getUsern(),
                entity.getPassword(),
                entity.getIsUse(),
                entity.getLoginCount(),
                entity.getLastLoginDate(),
                entity.getLasetLoginInfo(),
                entity.getRoleNo(),
                entity.getRealName(),
                entity.getPoliceNo(),
                entity.getSex(),
                entity.getDepartmentId(),
                entity.getLastLoginIp(),
                entity.getPhone(),
                entity.getId()
        });
    }

    @Override
    public CommonAdminuser find(Long id) {
        final String sql = " select * from common_adminuser where id = ? and is_delete = 0 ";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{id}, new CommonAdminuserRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public List<CommonAdminuser> findByDep(Long id) {
        final String sql = " select * from common_adminuser where id = ? and is_delete = 0 ";
        try {
            return jdbcTemplate.query(sql, new Object[]{id}, new CommonAdminuserRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public CommonAdminuser findByUsern(String usern) {
        final String sql = " select * from common_adminuser where (usern = ? or police_no = ? ) and is_delete = 0";

        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{usern,usern}, new CommonAdminuserRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }
    @Override
    public List<CommonAdminuser> findByRoleNo() {
        final String sql = "select * from common_adminuser where is_delete = 0 and role_no ='1002'";

        try {
            return jdbcTemplate.query(sql, new Object[]{}, new CommonAdminuserRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public void save(List<CommonAdminuser> list) {
        if (null != list && list.size() > 0) {
            final String sql = " insert into common_adminuser (uuid,add_info,add_date,add_user,update_date,update_info,update_user,usern,password,is_use,login_count,last_login_date,laset_login_info,is_delete,role_no,real_name,police_no,sex,department_id,add_ip,update_ip,last_login_ip,phone) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            List
                    <Object[]> params = new ArrayList
                    <Object[]>();
            Object[] objArr = null;
            CommonAdminuser entity = null;
            for (int i = 0; i < list.size(); i++) {
                entity = list.get(i);
                objArr = new Object[23];
                objArr[0] = entity.getUuid();
                objArr[1] = entity.getAddInfo();
                objArr[2] = entity.getAddDate();
                objArr[3] = entity.getAddUser();
                objArr[4] = entity.getUpdateDate();
                objArr[5] = entity.getUpdateInfo();
                objArr[6] = entity.getUpdateUser();
                objArr[7] = entity.getUsern();
                objArr[8] = entity.getPassword();
                objArr[9] = entity.getIsUse();
                objArr[10] = entity.getLoginCount();
                objArr[11] = entity.getLastLoginDate();
                objArr[12] = entity.getLasetLoginInfo();
                objArr[13] = entity.getIsDelete();
                objArr[14] = entity.getRoleNo();
                objArr[15] = entity.getRealName();
                objArr[16] = entity.getPoliceNo();
                objArr[17] = entity.getSex();
                objArr[18] = entity.getDepartmentId();
                objArr[19] = entity.getAddIp();
                objArr[20] = entity.getUpdateIp();
                objArr[21] = entity.getLastLoginIp();
                objArr[22] = entity.getPhone();
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public void delete(List
                               <Long> ids) {
        if (null != ids && ids.size() > 0) {
            final String sql = " update common_adminuser set is_delete = 1 where id = ? ";
            List
                    <Object
                            []> params = new ArrayList
                    <Object
                            []>();
            Object[] objArr = null;
            for (int i = 0; i < ids.size(); i++) {
                objArr = new Object[1];
                objArr[0] = ids.get(i);
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public void update(List<CommonAdminuser> list) {
        if (null != list && list.size() > 0) {
            final String sql = " update common_adminuser set add_info=?,update_info=?,usern=?,password=?,is_use=?,login_count=?,last_login_date=?,laset_login_info=?,role_no=?,real_name=?,police_no=?,sex=?,department_id=?,last_login_ip=?,phone=? where id = ?";
            List
                    <Object
                            []> params = new ArrayList
                    <Object
                            []>();
            Object[] objArr = null;
            CommonAdminuser entity = null;
            for (int i = 0; i < list.size(); i++) {
                entity = list.get(i);
                objArr = new Object[15];
                objArr[0] = entity.getAddInfo();
                objArr[1] = entity.getUpdateInfo();
                objArr[2] = entity.getUsern();
                objArr[3] = entity.getPassword();
                objArr[4] = entity.getIsUse();
                objArr[5] = entity.getLoginCount();
                objArr[6] = entity.getLastLoginDate();
                objArr[7] = entity.getLasetLoginInfo();
                objArr[8] = entity.getRoleNo();
                objArr[9] = entity.getRealName();
                objArr[10] = entity.getPoliceNo();
                objArr[11] = entity.getSex();
                objArr[12] = entity.getDepartmentId();
                objArr[13] = entity.getLastLoginIp();
                objArr[14] = entity.getPhone();
                objArr[15] = entity.getId();
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public PageBean<CommonAdminuser> page(int nowPage, int pageSize, ConditionEntity conditionEntity) {
        SQLEntity sqlEntity = ConditionTools.conditionEntities2SQL(conditionEntity);
        final String sql = " select * from common_adminuser where 1 = 1 and is_delete = 0 " + sqlEntity.getSql() + " order by " + sqlEntity.getOrder();
        return new PageBean<CommonAdminuser>(sql, sqlEntity.getParams(), nowPage, pageSize,
                new CommonAdminuserRowerMapper(), jdbcTemplate);
    }
}


class CommonAdminuserRowerMapper implements RowMapper<CommonAdminuser> {
    @Override
    public CommonAdminuser mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        Set
                <String> fieldSet = new HashSet
                <String>();
        for (int i = 1; i <= columnCount; i++) {
            fieldSet.add(rsmd.getColumnName(i));
        }
        CommonAdminuser entity = new CommonAdminuser();
        if (fieldSet.contains("police_no") && null !=
                rs.getObject("police_no")) {
            entity.setPoliceNo(rs.getString
                    ("police_no"));
        }
        if (fieldSet.contains("add_date") && null !=
                rs.getObject("add_date")) {
            entity.setAddDate(new
                    java.util.Date(rs.getTimestamp("add_date").getTime()));
        }
        if (fieldSet.contains("real_name") && null !=
                rs.getObject("real_name")) {
            entity.setRealName(rs.getString
                    ("real_name"));
        }
        if (fieldSet.contains("update_ip") && null !=
                rs.getObject("update_ip")) {
            entity.setUpdateIp(rs.getString
                    ("update_ip"));
        }
        if (fieldSet.contains("uuid") && null !=
                rs.getObject("uuid")) {
            entity.setUuid(rs.getString
                    ("uuid"));
        }
        if (fieldSet.contains("login_count") && null !=
                rs.getObject("login_count")) {
            entity.setLoginCount(rs.getInt
                    ("login_count"));
        }
        if (fieldSet.contains("password") && null !=
                rs.getObject("password")) {
            entity.setPassword(rs.getString
                    ("password"));
        }
        if (fieldSet.contains("update_user") && null !=
                rs.getObject("update_user")) {
            entity.setUpdateUser(rs.getString
                    ("update_user"));
        }
        if (fieldSet.contains("last_login_ip") && null !=
                rs.getObject("last_login_ip")) {
            entity.setLastLoginIp(rs.getString
                    ("last_login_ip"));
        }
        if (fieldSet.contains("id") && null !=
                rs.getObject("id")) {
            entity.setId(rs.getLong
                    ("id"));
        }
        if (fieldSet.contains("laset_login_info") && null !=
                rs.getObject("laset_login_info")) {
            entity.setLasetLoginInfo(rs.getString
                    ("laset_login_info"));
        }
        if (fieldSet.contains("is_use") && null !=
                rs.getObject("is_use")) {
            entity.setIsUse(rs.getBoolean
                    ("is_use"));
        }
        if (fieldSet.contains("add_info") && null !=
                rs.getObject("add_info")) {
            entity.setAddInfo(rs.getString
                    ("add_info"));
        }
        if (fieldSet.contains("usern") && null !=
                rs.getObject("usern")) {
            entity.setUsern(rs.getString
                    ("usern"));
        }
        if (fieldSet.contains("department_id") && null !=
                rs.getObject("department_id")) {
            entity.setDepartmentId(rs.getLong
                    ("department_id"));
        }
        if (fieldSet.contains("sex") && null !=
                rs.getObject("sex")) {
            entity.setSex(rs.getInt
                    ("sex"));
        }
        if (fieldSet.contains("update_info") && null !=
                rs.getObject("update_info")) {
            entity.setUpdateInfo(rs.getString
                    ("update_info"));
        }
        if (fieldSet.contains("last_login_date") && null !=
                rs.getObject("last_login_date")) {
            entity.setLastLoginDate(new
                    java.util.Date(rs.getTimestamp("last_login_date").getTime()));
        }
        if (fieldSet.contains("update_date") && null !=
                rs.getObject("update_date")) {
            entity.setUpdateDate(new
                    java.util.Date(rs.getTimestamp("update_date").getTime()));
        }
        if (fieldSet.contains("is_delete") && null !=
                rs.getObject("is_delete")) {
            entity.setIsDelete(rs.getBoolean
                    ("is_delete"));
        }
        if (fieldSet.contains("add_ip") && null !=
                rs.getObject("add_ip")) {
            entity.setAddIp(rs.getString
                    ("add_ip"));
        }
        if (fieldSet.contains("phone") && null !=
                rs.getObject("phone")) {
            entity.setPhone(rs.getString
                    ("phone"));
        }
        if (fieldSet.contains("role_no") && null !=
                rs.getObject("role_no")) {
            entity.setRoleNo(rs.getString
                    ("role_no"));
        }
        if (fieldSet.contains("add_user") && null !=
                rs.getObject("add_user")) {
            entity.setAddUser(rs.getString
                    ("add_user"));
        }
        return entity;
    }
}